package com.innovation.chengzhangriji.ui;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.util.FileUtils;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

import org.apache.http.Header;

import java.io.File;

public class TimelinePlayActivity extends BaseActivity {

    private VideoView mVideo;

    private CuteTextView mTextProgress;

    private ImageView mBtnPlay;

    private boolean complete;

    private boolean destroy;

    private String url;

    private String path;

    private int heightTop;

    private int heightBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupLayout();
        Bundle bundle = getIntent().getExtras();
        String uuid = bundle.getString("uuid");
        url = bundle.getString("url");
        String localUrl = bundle.getString("localUrl");
        if (TextUtils.isEmpty(localUrl)) {
            localUrl = DatabaseManager.getInstance(this).queryTimelineVideoLocalUrl(uuid);
        }
        if (TextUtils.isEmpty(localUrl)) {
            Log.d("url", "" + url);
            startDownloadVideo(url);
        } else {
            complete = true;
            Log.d("localUrl", "" + localUrl);
            mTextProgress.setVisibility(View.INVISIBLE);
            play(localUrl);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy = true;
        if (!complete) {
            Log.d("onDestroy", "执行了");
            if (!TextUtils.isEmpty(path)) {
                FileUtils.deleteFile(path);
                DatabaseManager.getInstance(TimelinePlayActivity.this).updateUnSyncTimelineVideoUrl(url);
            }
        }
        mVideo.stopPlayback();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float y = event.getY();
        // 判断点击的位置
        if (y <= heightTop || y >= heightBottom) {
            finish();
        } else {
            // 判断视频是否正在播放
            if (!mVideo.isPlaying() && complete) {
                mBtnPlay.setVisibility(View.INVISIBLE);
                mVideo.start();
            }
        }
        return true;
    }

    private void setupLayout() {
        setContentView(R.layout.activity_timeline_play);
        mVideo = (VideoView) findViewById(R.id.video);
        mVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mBtnPlay.setVisibility(View.VISIBLE);
            }
        });

        mTextProgress = (CuteTextView) findViewById(R.id.text_progress);
        FrameLayout layoutTop = (FrameLayout) findViewById(R.id.layout_top);
        FrameLayout layoutBottom = (FrameLayout) findViewById(R.id.layout_bottom);
        DisplayMetrics dm = getResources().getDisplayMetrics();

        int w = dm.widthPixels;
        int h = (int) ((dm.heightPixels - 240 * dm.density) / 2);

        heightTop = h;
        heightBottom = dm.heightPixels - h;

        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(w, h);
        lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutTop.setLayoutParams(lp1);

        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(w, h);
        lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutBottom.setLayoutParams(lp2);

        mBtnPlay = (ImageView) findViewById(R.id.btn_play);
    }

    private void setTextProgress(int progress) {
        if (progress < 0 || progress > 100) {
            return;
        }
        mTextProgress.setTextSize(10);
        mTextProgress.setTextColor(Color.WHITE);
        mTextProgress.setText(progress + "%");
    }

    private void startDownloadVideo(final String url) {
        File file = Config.createFile(this, Config.VIDEO_DIR);
        path = file.getPath();
        Client.downloadFile(this, url, new FileAsyncHttpResponseHandler(file) {

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                int progress = (int) (bytesWritten * 1.0f / totalSize * 100);
                setTextProgress(progress);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                String localUrl = file.getPath();
                DatabaseManager.getInstance(TimelinePlayActivity.this).updateUnSyncTimelineVideoUrl(url, localUrl);
                mTextProgress.setVisibility(View.INVISIBLE);
                play(localUrl);
                complete = true;
                Log.d("onSuccess", "执行了" + complete);

                if (destroy) {
                    if (!TextUtils.isEmpty(path)) {
                        FileUtils.deleteFile(path);
                        DatabaseManager.getInstance(TimelinePlayActivity.this).updateUnSyncTimelineVideoUrl(url);
                    }
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                DatabaseManager.getInstance(TimelinePlayActivity.this).updateUnSyncTimelineVideoUrlError(url);
//                mTextProgress.setVisibility(View.INVISIBLE);
                mTextProgress.setTextColor(Color.parseColor("#ff3745"));
                mTextProgress.setTextSize(20);
                mTextProgress.setText(getString(R.string.tip_video_download_failed));
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                mTextProgress.setTextColor(Color.parseColor("#ff3745"));
                mTextProgress.setTextSize(20);
                mTextProgress.setText(getString(R.string.tip_video_download_failed));
            }
        });
    }

    private void play(String url) {
        mVideo.setVideoPath(url);
        mVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideo.setBackgroundColor(Color.TRANSPARENT);
            }
        });
        mVideo.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(complete && mVideo.isPlaying() && mVideo.canPause()) {
            mVideo.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(complete) {
            mVideo.start();
        }
    }
}
